package com.lanhao.aot.mail;

import java.util.Map;

import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.beust.jcommander.internal.Maps;

import freemarker.template.Template;

public class FreeMarkerTemplateUtil {
	
	public static String getMailText(FreeMarkerConfigurer freeMarkerConfigurer, String templateName, Map<String, Object> map) throws Exception {
		// 通过指定模板名获取FreeMarker模板实例
		Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
		// FreeMarker通过Map传递动态数据
		// 解析模板并替换动态数据，最终content将替换模板文件中的${content}标签。
		String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
		return htmlText;
	}
	
	public static void main(String[] args) {
		try {
			FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
			factory.setTemplateLoaderPaths("classpath:tpl");
			factory.setDefaultEncoding("UTF-8");
			FreeMarkerConfigurer result = new FreeMarkerConfigurer();
			result.setConfiguration(factory.createConfiguration());
			String mailText = getMailText(result, "email_template.ftl", Maps.newHashMap());
			System.out.println(mailText);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
